package cn.xawl.gulimall.product.service.impl;

import cn.xawl.common.constant.ProductConstant;
import cn.xawl.gulimall.product.entity.AttrAttrgroupRelationEntity;
import cn.xawl.gulimall.product.entity.AttrGroupEntity;
import cn.xawl.gulimall.product.service.AttrAttrgroupRelationService;
import cn.xawl.gulimall.product.service.AttrGroupService;
import cn.xawl.gulimall.product.service.CategoryService;
import cn.xawl.gulimall.product.vo.AttrResVo;
import cn.xawl.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.xawl.common.utils.PageUtils;
import cn.xawl.common.utils.Query;

import cn.xawl.gulimall.product.dao.AttrDao;
import cn.xawl.gulimall.product.entity.AttrEntity;
import cn.xawl.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Transactional
@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private CategoryService categoryService;

    private final ProductConstant.AttrTypeEnum saleType = ProductConstant.AttrTypeEnum.ATTR_SALE_TYPE;
    private final ProductConstant.AttrTypeEnum baseType = ProductConstant.AttrTypeEnum.ATTR_BASE_TYPE;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        //将获取到的视图对象赋值给数据库对象
        BeanUtils.copyProperties(attrVo, attrEntity);
        //保存该对象
        this.save(attrEntity);
        //在属性 和 属性组 的关联表中插入数据(若属性类型为销售属性则不需要加入关联表)
        if (attrVo.getAttrType() == ProductConstant.AttrTypeEnum.ATTR_BASE_TYPE.getType()) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            //保存关联数据
            attrAttrgroupRelationService.save(relationEntity);
        }
    }

    @Override
    public PageUtils getAttrList(Map<String, Object> params, Long catalogId, String type) {
        //创建自定义
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", "base".equalsIgnoreCase(type) ? baseType.getType() : saleType.getType());
        //获取查询关键字
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page;

        if (catalogId != 0) {
            queryWrapper.eq("catalog_id", catalogId);
        }
        page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        //船舰返回对象
        PageUtils pageUtils = new PageUtils(page);

        //获取当前page中的记录
        List<AttrEntity> attrEntities = page.getRecords();
        //创建一个试图界面正真需要的对象
        //给Vo对象赋值
        List<AttrResVo> collect = attrEntities.stream().map((attrEntity) -> {
            AttrResVo attrResVo = new AttrResVo(); //这里定义视图对象时要定义在循环内部，否则会重复赋值
            BeanUtils.copyProperties(attrEntity, attrResVo);
            //TODO  此处可能会有空指针异常！
            if ("base".equalsIgnoreCase(type)) {
                //若类型是销售类型，则不需要查询分组信息
//                attrResVo.setGroupName(attrGroupService.getById(attrAttrgroupRelationService.getById(attrEntity.getAttrId()).getAttrGroupId()).getAttrGroupName());
                //根据attrId查询关联表中的数据
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (relationEntity != null) {
                    //根据关联表中的attrGroupId查询AttrGroupEntity信息
                    AttrGroupEntity attrGroupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                    if (attrGroupEntity != null) {
                        //为响应试图对象赋值
                        attrResVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }


            }
            attrResVo.setCatalogName(categoryService.getById(attrEntity.getCatalogId()).getName());

            return attrResVo;
        }).collect(Collectors.toList());
        //将返回的pageUtils对象重新设置list值为vo对象的list
        pageUtils.setList(collect);
        return pageUtils;
    }

    @Override
    public AttrResVo getAttrDetail(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrResVo attrResVo = new AttrResVo();
        BeanUtils.copyProperties(attrEntity, attrResVo);

        AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        if (relationEntity != null) {
            attrResVo.setAttrGroupId(relationEntity.getAttrGroupId());
        }
        attrResVo.setCatalogPath(attrGroupService.getCatalogPathById(attrResVo.getCatalogId()));

        return attrResVo;

    }

    @Override
    public void updateAttrRelation(AttrVo attrVo) {
        //先将获取的试图对象复制给attr数据对象，并更新数据库中的数据
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.updateById(attrEntity);

        //修改关联关系
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        Long attrId = attrVo.getAttrId();
        Long attrGroupId = attrVo.getAttrGroupId();
        relationEntity.setAttrGroupId(attrGroupId);
        relationEntity.setAttrId(attrId);
        //增加更新属性与属性分组关联表时的条件（解决了更新时更新了所有数据的错误）
        UpdateWrapper<AttrAttrgroupRelationEntity> updateWrapper = new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId).and((wrapper) ->{
            wrapper.eq("attr_group_id", attrGroupId);
        } );
        attrAttrgroupRelationService.saveOrUpdate(relationEntity, updateWrapper);
    }

}